package com.lagou.controller;

import com.github.pagehelper.PageInfo;
import com.lagou.common.Const;
import com.lagou.common.ResponseCode;
import com.lagou.common.ServerResponse;
import com.lagou.model.User;
import com.lagou.service.IuserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/user")
@Transactional
public class UserController {

    @Autowired
    private IuserService userService;

    //1. 用户登录模块
    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> login(String username, String password, HttpSession session) {
        //调用service的登录方法，放回以个ServerResponse<User>

        ServerResponse<User> response = userService.login(username, password);

        //判断是否登录成功，成功则把用户放到session中

        if(response.getStatus() == ResponseCode.SUCCESS.getCode()) {
            session.setAttribute(Const.CURRENT_USER, response.getData());
        }
        //返回ServerResponse
        return response;
    }

    //2.用户分页列表模块
    //分页查询user


    @RequestMapping(value = "list.do", method = RequestMethod.POST)
    @ResponseBody
    public  ServerResponse<PageInfo> list(@RequestParam(value="pageNum",defaultValue = "1") Integer pageNum,
                                          @RequestParam(value="pageSize",defaultValue = "10")Integer pageSize) {
        ServerResponse<PageInfo> users = userService.getUsers(pageNum, pageSize);
        return users;
    }

    @RequestMapping(value = "add.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> add(User user) {
        return userService.add(user);
    }

    @RequestMapping(value = "deleteUser.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> delete(int id){
        return userService.deleteByPrimary(id);
    }


    @RequestMapping(value = "edit.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> edit (User user) {
        return userService.edit(user);
    }

    @RequestMapping(value = "findById.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> findById (int id) {
        return userService.findById(id);
    }
}
